package com.clear.gateway.filter;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.google.gson.Gson;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * <p>
 * 登录过滤器 由Gateway提供
 * <p>
 * 目的：解析tokenInfo，拿到loginId，存入header。后续所有操作header中都需要携带loginId
 */
@Component
@Order(-1)  // 过滤器顺序
@Slf4j
public class LoginFilter implements GlobalFilter { // GlobalFilter：可处理一切进入网关的请求和微服务响应

    /**
     * 处理当前请求，有必要的话通过{@link GatewayFilterChain}将请求交给下一个filter处理
     *
     * @param exchange 请求上下文 包含req、resp等
     * @param chain    用来把请求委托给下一个filter
     * @return {@code Mono<Void>}返回标示当前过滤器业务结束
     */
    @Override
    @SneakyThrows
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取request
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();

        String url = request.getURI().getPath();
        log.info("LoginFilter.filter.url: {}", url);
        // 如果是登录，直接放行
        if ("/user/doLogin".equals(url)) {
            return chain.filter(exchange);
        }
        System.out.println(StpUtil.isLogin() + "ssssss");
        // ======解析token，拿到loginId=======
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        log.info("LoginFilter.filter.tokenInfo:{}", new Gson().toJson(tokenInfo));

        String loginId = (String) tokenInfo.getLoginId();
        mutate.header("loginId", loginId);

        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }
}

